package indi.coffeenc.queuedownloader.plugin.util;

import indi.coffeenc.queuedownloader.TaskHolder;
import indi.coffeenc.queuedownloader.strategy.Task;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 默认的下载插件，不对链接进行处理
 * 直接将其封装成一个Task
 */
public class Simple implements Filter {

    public boolean doFilter(String url) {
        long size = 0;
        try {
            size = getFileSize(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        /**
         * 创建一个Task，Task的URL列表只存储源URL一个
         */
        Task task = new Task();
        task.setSource(url);
        Task.URL url1 = new Task.URL(url).setTotal(size);
        task.add(url1);
        /**
         * 将创建的Task添加到TaskHolder中
         */
        TaskHolder.add(task);
        return true;
    }

    /**
     * 获取目标网络文件的大小
     */
    private long getFileSize(String url) throws IOException {
        URL url0 = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) url0.openConnection();
        conn.setRequestMethod("GET");
        conn.connect();
        return conn.getContentLengthLong();
    }
}

